package com.ictech.print.ui;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.ictech.client.R;

import java.util.ArrayList;
import java.util.Set;

public class Activity_DeviceList extends Activity {
    // 调试用
    private final String TAG = "Activity_DeviceList";

    // 返回时数据标签
    public static String EXTRA_DEVICE_ADDRESS = "printerMac";

    // 成员域
    private BluetoothAdapter mBtAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;
    private ArrayList<BluetoothDevice> mNewDeviceList;

    private Button Scan;
    private Button Cancel;
    private TextView TitlePairedDevices;
    private TextView TitleNewdDevices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);  //设置窗口显示模式为窗口方式
        setContentView(R.layout.activity_devicelist);

        // 设定默认返回值为取消
        setResult(Activity.RESULT_CANCELED);

        // 设定扫描按键响应
        Scan = (Button) findViewById(R.id.bt_adScan);
        Cancel = (Button) findViewById(R.id.bt_adCancel);
        TitlePairedDevices = (TextView) findViewById(R.id.tv_adPairedDevices);
        TitleNewdDevices = (TextView) findViewById(R.id.tv_adNewDevices);

        // 得到本地蓝牙句柄
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();

        RegisterBroadcastReceiver();
        ListInit();
        ButtonInit();
    }

    private void ButtonInit() {
        Scan.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // 改变标题并显示等待图标
                setProgressBarIndeterminateVisibility(true);
                setTitle("查找设备中...");
                // 显示标题
                TitleNewdDevices.setVisibility(View.VISIBLE);
                mNewDevicesArrayAdapter.clear();
                // 关闭再进行的服务查找
                if (mBtAdapter.isDiscovering()) {
                    mBtAdapter.cancelDiscovery();
                }
                mBtAdapter.startDiscovery();
                v.setVisibility(View.GONE);
            }
        });

        Cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void ListInit() {
        // 初使化设备存储数组
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.item_device);
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.item_device);
        mNewDeviceList = new ArrayList<BluetoothDevice>();

        // 设置已配队设备列表
        ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 准备连接设备，关闭服务查找
                if (mBtAdapter.isDiscovering()) {
                    mBtAdapter.cancelDiscovery();
                }
                // 得到mac地址
                String info = ((TextView) view).getText().toString();
                String address = info.substring(info.length() - 17);

                // 设置返回数据
                Intent intent = new Intent();
                intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

                // 设置返回值并结束程序
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        // 设置没配对设备列表
        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
        newDevicesListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 准备连接设备，关闭服务查找
                if (mBtAdapter.isDiscovering()) {
                    mBtAdapter.cancelDiscovery();
                }
                /*绑定设备*/
                createBond(mNewDeviceList.get(position));
            }
        });

        // 得到已配对蓝牙设备列表
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            TitlePairedDevices.setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices) {
//                Log.i(TAG ,"设备类型为：" +device.getBluetoothClass().getMajorDeviceClass());
                mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        } else {
//            mPairedDevicesArrayAdapter.add("No devices have been paired");
        }
    }

    // 选择设备响应函数
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // 准备连接设备，关闭服务查找
            if (mBtAdapter.isDiscovering()) {
                mBtAdapter.cancelDiscovery();
            }
            // 得到mac地址
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            // 设置返回数据
            Intent intent = new Intent();
            intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

            // 设置返回值并结束程序
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    };

    /*开始设备绑定*/
    private boolean createBond(BluetoothDevice device) {
        return device.createBond();
    }


    private void RegisterBroadcastReceiver() {
        // 注册接收查找到设备action接收器
        IntentFilter mfilter = new IntentFilter();
        mfilter.addAction(BluetoothDevice.ACTION_FOUND);
        mfilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mfilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        mfilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);      //配对状态改变
        mfilter.setPriority(1000);      //优先级为-1000~1000
        registerReceiver(mReceiver, mfilter);
    }

    // 查找到设备和搜索完成action监听器
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 查找到设备action
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {      //扫描到蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                BluetoothClass deviceClass = intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS);
//                Log.i(TAG, "类型为：" + deviceClass.getMajorDeviceClass());
                // 记录并显示没有进行配对的蓝牙设备
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDeviceList.add(device);
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
//                Log.e(TAG, device.getName() + "---" + device.getAddress());
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {     //扫描结束
                setProgressBarIndeterminateVisibility(false);
                setTitle("选择要连接的设备");
                if (mNewDevicesArrayAdapter.getCount() == 0) {
//                    mNewDevicesArrayAdapter.add("No devices have been found");
                    Scan.setVisibility(View.VISIBLE);
                }
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {      //设备绑定
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_BONDING:{
                        Log.d(TAG, "正在配对......");
                    }break;
                    case BluetoothDevice.BOND_BONDED:{
                        /*将配对的设备放到配对列表中*/
                        mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                        mPairedDevicesArrayAdapter.notifyDataSetChanged();
                        /*将配对的设备从未配对列表中删除*/
                        mNewDevicesArrayAdapter.remove(device.getName() + "\n" + device.getAddress());
                        mNewDevicesArrayAdapter.notifyDataSetChanged();
                        Log.d(TAG, "完成配对");
                    }break;
                    case BluetoothDevice.BOND_NONE:{
                        Log.d(TAG, "取消配对");
                    }break;
                    default:break;
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 关闭服务查找
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }

        // 注销action接收器
        this.unregisterReceiver(mReceiver);
    }
}
